//
// Created by ASUS on 2025/4/27.
//

#ifndef MYARRAY_MYARRARY_HPP
#define MYARRAY_MYARRARY_HPP
#include <iostream>
#include <string>
using namespace std;

template <class T>
class MyArrary{
public:
// 构造函数，用于初始化数组大小
    MyArrary(int capacity){
//    cout<<"MyArrary(int capacity)"<<endl;
    this->capacity = capacity;
    this->size = 0;
    this->pAddress = new T[capacity];
    }

//析构函数，用于释放内存
    ~MyArrary(){
//    cout<<"~MyArrary()"<<endl;
    if(this->pAddress != nullptr){
        delete[] this->pAddress;
        this->pAddress = nullptr;
        }
    }

    //拷贝构造
    MyArrary(const MyArrary &arr){
//    cout<<"MyArrary(const MyArrary &arr)"<<endl;
    this->size=arr.size;
    this->capacity=arr.capacity;

    //深拷贝
    this->pAddress=new T[arr.capacity];
    for(int i=0;i<arr.size;i++){
        this->pAddress[i]=arr.pAddress[i];
        }
    }

    //赋值运算符重载,防止浅拷贝问题
    MyArrary& operator=(const MyArrary &arr){
//    cout<<"operator=(const MyArrary &arr)"<<endl;
    //先判断原来有无数据
    if(this->pAddress != nullptr){
        //释放原来的内存
        delete[] this->pAddress;
        //将指针置为空
        this->pAddress = nullptr;
        //将size和capacity置为0
        this->size = 0;
        this->capacity = 0;
        }

    //深拷贝
    //将size和capacity赋值为arr的size和capacity
    this->size=arr.size;
    this->capacity=arr.capacity;
    //为pAddress分配内存
    this->pAddress=new T[arr.capacity];
    //将arr的pAddress中的数据拷贝到this的pAddress中
    for(int i=0;i<arr.size;i++){
        this->pAddress[i]=arr.pAddress[i];
        }
    //返回*this
    return *this;
    }

    //尾插法
    void push_back(const T &value){
    //判断数组是否已满
    if(this->size >= this->capacity){
        cout<<"数组已满"<<endl;
        return;
        }
    //将元素插入到数组末尾
    this->pAddress[this->size] = value;
    //更新数组大小
    this->size++;
    }


    //尾删法
    void pop_back(){
    //判断数组是否为空
    if(this->size <= 0){
        cout<<"数组为空"<<endl;
        return;
        }
    //将数组大小减1
    this->size--;
}

//下标访问元素
    T& operator[](int index){
    //返回this指针指向的pAddress数组的第index个元素
    return this->pAddress[index];
}


//返回数组大小
    int getSize(){
    return this->size;
    }

//返回数组容量
    int getCapacity(){
    //返回this指针指向的对象的capacity成员变量
    return this->capacity;

}


//返回数组大小
    int GetSize(){
    //获取数组大小
    return this->size;

}

//打印数组
    void printArr(){
    //遍历数组
    for(int i=0;i<this->size;i++){
        //打印数组元素
        cout<<this->pAddress[i]<<" ";
        }
    //换行
    cout<<endl;
    }

private:
    //the pointer to the first element
    T *pAddress;
    //the size of the array
    int size;
    //the capacity size of the array
    int capacity;

};



#endif //MYARRAY_MYARRARY_HPP
